
//
//  SEGNewSignViewController.m
//  SignDemo
//
//  Created by Clavis on 2018/11/12.
//  Copyright © 2018 Clavis. All rights reserved.
//

#import "SEGSignViewController.h"

@interface SEGSignViewController ()

@property(nonatomic,assign) CGPoint lastPoint;
@property(nonatomic,assign) CGPoint controlPoint;
@property(nonatomic,assign) CGFloat beforeLength;
@property(nonatomic,assign) BOOL isSwiping;
@property(nonatomic,strong) NSMutableArray * xPoints;
@property(nonatomic,strong) NSMutableArray * yPoints;
@property(nonatomic,strong) UIImageView * imageView;
@property(nonatomic, strong) UIBezierPath *bezier;
@property (nonatomic, strong) NSMutableArray *cacheImageArray; //存储Undo出来的线条
@property (nonatomic, strong) UIButton *tip;

@end

@implementation SEGSignViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    self.cacheImageArray = [NSMutableArray new];
}

#pragma  mark 横屏设置
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //强制旋转竖屏
    [self forceOrientationLandscape];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    //强制旋转竖屏
    [self forceOrientationPortrait];
}

- (BOOL)prefersStatusBarHidden {
    return NO;
}

- (void)setupUI {
    self.title = @"签字";
    self.view.backgroundColor = [UIColor seg_setColorWithAny:kColor_W dark:[UIColor colorWithHexString:@"#999999"]];
    UIButton *revertButton = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 50, 30);
        [button setTitle:@"撤销" forState:UIControlStateNormal];
        [button setTitleColor:kColor_1 forState:UIControlStateNormal];
        button.titleLabel.font = kFont_13;
        [button addTarget:self action:@selector(revertImageSign) forControlEvents:UIControlEventTouchUpInside];
        button;
    });
    UIBarButtonItem *revertItem = [[UIBarButtonItem alloc] initWithCustomView:revertButton];
    UIButton *clearButton = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 50, 30);
        [button setTitle:@"清空" forState:UIControlStateNormal];
        [button setTitleColor:kColor_1 forState:UIControlStateNormal];
        button.titleLabel.font = kFont_13;
        [button addTarget:self action:@selector(clearImageSign) forControlEvents:UIControlEventTouchUpInside];
        button;
    });
    UIBarButtonItem *clearItem = [[UIBarButtonItem alloc] initWithCustomView:clearButton];
    self.navigationItem.rightBarButtonItems = @[clearItem, revertItem];
    
    UILabel * tipLabel = [[UILabel alloc] init];
    tipLabel.text = @"   签字将会作为企业收款的凭证，请书写时尽量保持笔迹清晰工整";
    tipLabel.textColor = kColor_T;
    tipLabel.backgroundColor = [UIColor colorWithHexString:@"#fefede"];
    tipLabel.font = kFont_14;
    tipLabel.numberOfLines = 0;
    [self.view addSubview:tipLabel];
    
    UIButton *saveBtn  = [UIButton buttonWithType:UIButtonTypeCustom];
    [saveBtn setTitle:@"提交" forState:UIControlStateNormal];
    [saveBtn setTitleColor:kColor_W forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(saveImageSign) forControlEvents:UIControlEventTouchUpInside];
    saveBtn.titleLabel.font = kFont_17;
    saveBtn.backgroundColor = kColor_T;
    [saveBtn setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateNormal];
    [saveBtn setBackgroundImage:[UIImage imageWithColor:kColor_T_Press] forState:UIControlStateHighlighted];
    CGFloat safeArea = LYIsiPhoneX() ? 20 : 0;
    saveBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, safeArea, 0);
    [self.view addSubview:saveBtn];
    
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0,0,0)];
    [self.view addSubview:self.imageView];
    
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.top.equalTo(self.view);
        make.height.mas_equalTo(34);
    }];
    
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(40.0 + safeArea);
        make.bottom.equalTo(self.view);
    }];
    
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.top.equalTo(tipLabel.mas_bottom);
        make.bottom.equalTo(saveBtn.mas_top);
    }];
}

//保存操作
- (void)saveImageSign {
    //传照片的值过去
    UIImage *image = [self getSignImage];
    if (!image) {
        [SEGAlertView showTmepMessageWithMessage:@"您还未签字"];
        return;
    }
    if (self.completeBlock) {
        self.completeBlock(image);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

//清空操作
- (void)clearImageSign {
    self.imageView.image = nil;
    self.cacheImageArray = [NSMutableArray new];
}

- (void)revertImageSign {
    [self.cacheImageArray removeLastObject];
    self.imageView.image = self.cacheImageArray.lastObject;
}

- (UIImage *)getSignImage {
    if (self.cacheImageArray.count == 0) {
        return nil;
    }
    UIImage *image = [self imageRepresentation];
    return [self addWatermark:image];
}

- (UIImage *)imageRepresentation {
    //开启图形上下文
    UIGraphicsBeginImageContextWithOptions(self.imageView.frame.size, NO, 0);
    //获取当前上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //渲染
    [self.imageView.layer renderInContext:ctx];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

/**
 添加水印
 */
- (UIImage *)addWatermark:(UIImage *)image {
    //开启图形上下文
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
    //绘制图片
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    //添加文字
    CGRect textBackRect = CGRectMake(self.imageView.size.width - 135, self.imageView.size.height - 33, 115, 18);
    CGRect textRect = CGRectMake(textBackRect.origin.x + 4, textBackRect.origin.y + 3, 120, 18);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextAddRect(context, textBackRect);
    [[UIColor blackColor] set];
    CGContextFillPath(context);
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *text = [formatter stringFromDate:[NSDate date]];
    NSDictionary<NSAttributedStringKey, id> * attributes = @{NSForegroundColorAttributeName: [UIColor colorWithHexString:@"#CFDF3B"], NSFontAttributeName: [UIFont systemFontOfSize:10]};
    [text drawInRect:textRect withAttributes:attributes];
    
    //绘制水印
    UIImage *waterImage = [UIImage imageWithContentsOfFile:SEGPicName(@"AppIcon60_corner")];
    CGRect waterImageRect = CGRectMake(textBackRect.origin.x - 25, textBackRect.origin.y, 18, 18);
    [waterImage drawInRect:waterImageRect];
    
    //获取图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //关闭上下文
    UIGraphicsEndImageContext();
    return newImage;
}

static CGPoint midpoint(CGPoint p0,CGPoint p1) {
    return(CGPoint){(p0.x+p1.x)/2.0,(p0.y+p1.y)/2.0};
}

- (CGFloat)getLengthFormPoint:(CGPoint)point1 toPoint:(CGPoint)point2 {
    CGFloat a = (point1.x-point2.x)*(point1.x-point2.x);
    CGFloat b = (point1.y-point2.y)*(point1.y-point2.y);
    return sqrt(a+b);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    self.isSwiping    = false;
    UITouch * touch = touches.anyObject;
    self.lastPoint = [touch locationInView:self.imageView];
    self.controlPoint = self.lastPoint;
    [self.xPoints addObject:[NSNumber numberWithFloat:self.lastPoint.x]];
    [self.yPoints addObject:[NSNumber numberWithFloat:self.lastPoint.y]];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch * touch = touches.anyObject;
    CGPoint currentPoint = [touch locationInView:self.imageView];
    CGPoint midPoint=midpoint(self.controlPoint,currentPoint);
    NSInteger i = self.xPoints.count==0?0:self.xPoints.count-1;
    CGPoint startPoint;
    if(!self.isSwiping || i==0)
    {
        startPoint = self.lastPoint;
    }else{
        startPoint = CGPointMake([self.xPoints[i] floatValue], [self.yPoints[i] floatValue]);
    }
    CGPoint cpPoint = self.isSwiping?self.controlPoint:midPoint;
    CGPoint endPoint = self.isSwiping?midPoint:currentPoint;
    
    UIGraphicsBeginImageContext(self.imageView.frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self.imageView.image drawInRect:(CGRectMake(0, 0, self.imageView.frame.size.width, self.imageView.frame.size.height))];
    CGContextMoveToPoint(context, startPoint.x, startPoint.y);
    CGContextAddQuadCurveToPoint(context,cpPoint.x, cpPoint.y, endPoint.x, endPoint.y);//设置贝塞尔曲线的控制点坐标和终点坐标
    CGContextSetLineCap(context,kCGLineCapRound);
    CGFloat lenght = [self getLengthFormPoint:startPoint toPoint:endPoint];
    CGFloat offset = self.beforeLength==0?1:self.beforeLength/lenght;
    offset = MAX(0.85, offset);
    CGFloat width = MIN(5.0, 4.0*offset);
    CGContextSetLineWidth(context, width);
    CGContextSetRGBStrokeColor(context,0.0, 0.0, 0.0, 1.0);
    CGContextStrokePath(context);
    self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    self.lastPoint = midPoint;
    self.controlPoint = currentPoint;
    self.beforeLength = lenght;
    [self.xPoints addObject:[NSNumber numberWithFloat:self.lastPoint.x]];
    [self.yPoints addObject:[NSNumber numberWithFloat:self.lastPoint.y]];
    
    self.isSwiping = true;
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if(!self.isSwiping) {
        UIGraphicsBeginImageContext(self.imageView.frame.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        [self.imageView.image drawInRect:(CGRectMake(0, 0, self.imageView.frame.size.width, self.imageView.frame.size.height))];
        CGContextSetLineCap(context, kCGLineCapRound);
        CGContextSetLineWidth(context, 4.0);
        CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 1.0);
        CGContextMoveToPoint(context, self.lastPoint.x, self.lastPoint.y);
        CGContextAddLineToPoint(context, self.lastPoint.x, self.lastPoint.y);
        CGContextStrokePath(context);
        self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        [self.cacheImageArray addObject:self.imageView.image];
    } else {
        UIImage *image = [self imageRepresentation];
        [self.cacheImageArray addObject:image];
    }
}

#pragma mark getter && setter
- (NSMutableArray*)xPoints {
    if (!_xPoints) {
        _xPoints=[[NSMutableArray alloc]initWithCapacity:0];
    }
    return _xPoints;
}
- (NSMutableArray*)yPoints {
    if (!_yPoints) {
        _yPoints=[[NSMutableArray alloc]initWithCapacity:0];
    }
    return _yPoints;
}

@end
